package com.mobimap.nhom9.dao;

import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mobimap.nhom9.dao.table.IDTOConverter;
import com.mobimap.nhom9.dao.table.ITable;

public class TableDAO<DTO> {
	protected SQLiteDatabase database;
	protected ITable<DTO> table;

	public TableDAO(SQLiteDatabase db, ITable<DTO> table) {
		this.database = db;
		this.table = table;
	}

	public List<DTO> getAll() {
		Cursor cursor = this.database.query(table.getName(),
				table.getColumns(), null, null, null, null, null);
		List<DTO> result = QueryHelper.cursorToDTOs(cursor, table);
		cursor.close();
		return result;
	}

	public List<DTO> getDTOs(IQueryHandler<DTO> handler) {
		Cursor cursor = this.database.query(table.getName(),
				table.getColumns(), null, null, null, null, null);
		List<DTO> result = QueryHelper.cursorToDTOs(cursor, handler);
		cursor.close();
		return result;
	}

	public List<DTO> getDTOs(String selection) {
		return getDTOs(table.getColumns(), selection, table);
	}

	public List<DTO> getDTOs(String selection, IDTOConverter<DTO> converter) {
		return getDTOs(table.getColumns(), selection, converter);
	}

	public List<DTO> getDTOs(String[] columns, String selection,
			IDTOConverter<DTO> converter) {
		Cursor cursor = database.query(table.getName(), columns, selection,
				null, null, null, null);
		List<DTO> result = QueryHelper.cursorToDTOs(cursor, converter);
		cursor.close();
		return result;
	}

	public List<DTO> getDTOs(String[] columns, String selection,
			IQueryHandler<DTO> handler) {
		Cursor cursor = database.query(table.getName(), columns, selection,
				null, null, null, null);
		List<DTO> result = QueryHelper.cursorToDTOs(cursor, handler);
		cursor.close();
		return result;
	}
}
